
#import "XAlert.h"

#import <QuartzCore/QuartzCore.h>

#import "XMacro.h"
#import "XLog.h"
#import "XDefine.h"
#import "UIColor+X.h"
#import "UILabel+X.h"
#import "XLayerController.h"


@interface XAlert () {
    
}

@end


@implementation XAlert


/**
 * 创建标题
 * @param        title，标题
 * @result       返回创建的标题控件的视图
 */
- (UIView *)createTitle:(NSString *)title {
    CGRect rc = CGRectMake(10, 0, self.frame.size.width, 40);
    rc.size.width -= rc.origin.x * 2;
    UIView *vTitleBG = [[UIView alloc] initWithFrame:rc];
    vTitleBG.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MsgBoxTitleBG.png"]];
    
    if (X_CUSTOMMSGBOX_CORNERSTYLE) {
        vTitleBG.layer.cornerRadius = 5.0f;
        vTitleBG.layer.borderColor = [UIColor clearColor].CGColor;
        vTitleBG.layer.borderWidth = 1;
        vTitleBG.layer.masksToBounds = YES;
    }
    
    rc.origin = CGPointZero;
    UILabel *labTitle = [[UILabel alloc] initWithFrame:rc];
    labTitle.backgroundColor = [UIColor clearColor];
    labTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0f];
    labTitle.textAlignment = UITextAlignmentCenter;
    labTitle.textColor = [UIColor whiteColor];
    labTitle.text = self.title;
    [vTitleBG addSubview:labTitle];
    return vTitleBG;
}


/**
 * 创建消息
 * @param        message，消息
 * @result       返回创建的消息控件的视图
 */
- (UIView *)createMessage:(NSString *)message {
    CGRect rc = CGRectMake(20, 0, self.frame.size.width, 20);
    UIFont *font = [UIFont fontWithName:@"Helvetica" size:16.0f];
    rc.size.width -= rc.origin.x * 2;
    UILabel *labMessage = [[UILabel alloc] initWithFrame:rc];
    labMessage.backgroundColor = [UIColor clearColor];
    labMessage.numberOfLines = 0;
    labMessage.text = self.message;
    labMessage.font = font;
    labMessage.textColor = [UIColor blackColor];
    
    if ([self.message sizeWithFont:font].width <= rc.size.width - rc.origin.x * 2) {
        // 内容少于1行时，居中显示
        labMessage.textAlignment = UITextAlignmentCenter;
        return labMessage;
    }
    
    rc = [labMessage heightToFit];
    if (rc.size.height > 280) {
        // 高度超出了预设（采用滚动显示）
        rc = CGRectMake(0, 0, self.frame.size.width, 280);
        
        UIView *vContainer = [[UIView alloc] initWithFrame:rc];
        vContainer.backgroundColor = [UIColor clearColor];
        
        // 创建滚动窗口
        UIScrollView *scContainer = [[UIScrollView alloc] initWithFrame:rc];
        scContainer.backgroundColor = [UIColor clearColor];
        CGSize size = labMessage.frame.size;
        size.height += 30;
        scContainer.contentSize = size;
        rc = labMessage.frame;
        rc.origin.y += 15;
        labMessage.frame = rc;
        [scContainer addSubview:labMessage];
        [vContainer addSubview:scContainer];
        
        // 创建渐变蒙层
        UIView *vTop = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vContainer.frame.size.width, 15)];
        UIView *vBottom = [[UIView alloc] initWithFrame:CGRectMake(0, 0, vContainer.frame.size.width, 15)];
        
        NSMutableArray *arrColors = [[NSMutableArray alloc] initWithCapacity:0];
        NSInteger nStep = (NSInteger) (1 / 15);
        for (int i = 15; i > 0; i--) {
            UIColor *color = [UIColor colorWithHex:0xffffff andAlpha:nStep * i];
            [arrColors addObject:(id) color.CGColor];
        }
        
        CAGradientLayer *gradientTop = [CAGradientLayer layer];
        gradientTop.frame = vTop.frame;
        gradientTop.colors = arrColors;
        [vTop.layer insertSublayer:gradientTop atIndex:0];
        
        [arrColors removeAllObjects];
        for (int i = 0; i < 15; i++) {
            UIColor *color = [UIColor colorWithHex:0xffffff andAlpha:nStep * i];
            [arrColors addObject:(id) color.CGColor];
        }
        
        CAGradientLayer *gradientBottom = [CAGradientLayer layer];
        gradientBottom.frame = vBottom.frame;
        gradientBottom.colors = arrColors;
        [vBottom.layer insertSublayer:gradientBottom atIndex:0];
        
        [vContainer addSubview:vTop];
        rc = vBottom.frame;
        rc.origin.y = vContainer.frame.size.height - 15;
        vBottom.frame = rc;
        [vContainer addSubview:vBottom];
        
        return vContainer;
    }
    else {
        // 高度没有超出预设
        return labMessage;
    }
}


/**
 * 根据标题，创建按键
 * @param        title，按钮标题
 * @result       返回创建的按钮对象
 */
- (UIButton *)createButton:(NSString *)title atIndex:(NSInteger)index {
    CGRect rc = CGRectMake(10, 0, self.frame.size.width, 40);
    rc.size.width -= rc.origin.x * 2;
    UIButton *btn = [[UIButton alloc] initWithFrame:rc];
    btn.tag = index;
    [btn setBackgroundImage:[UIImage imageNamed:@"MsgBoxButtonA.png"]
                   forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"MsgBoxButtonB.png"]
                     forState:UIControlStateHighlighted];
    
    btn.layer.borderColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MsgBoxButtonBoder"]].CGColor;
    btn.layer.borderWidth = 1;
    if (X_CUSTOMMSGBOX_CORNERSTYLE) {
        btn.layer.cornerRadius = 5.0f;
        btn.layer.masksToBounds = YES;
    }
    
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    btn.titleLabel.font = [UIFont fontWithName:@"Helvetica" size:16.0f];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(onBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}


/**
 * 按钮点击事件处理
 * @param        id，被点击的按钮
 * @result
 */
- (void)onBtnClick:(id)sender {
    UIButton *btn = (UIButton *)sender;
    
    // 调用回调函数进行处理
    if (self.delegate && [self.delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)]) {
        [self.delegate alertView:self clickedButtonAtIndex:btn.tag];
    }
    
    // 关闭消息框
    [self close];
}


/**
  * 关闭当前告警框
  * @result
  */
- (void)close {
    [XLayerController removeLayer:self];
}


/**
 * 显示
 * @result
 */
- (void)show {
    // 用于记录主窗体的布局
    CGRect rc;
    CGRect rcMain = CGRectMake(20, 0, 280, 0);
    
    // 编辑主窗体 背景颜色
    self.backgroundColor = [UIColor whiteColor];
    self.frame = rcMain;
    if (X_CUSTOMMSGBOX_CORNERSTYLE) {
        self.layer.cornerRadius = 5.0f;
        self.layer.borderColor = [UIColor clearColor].CGColor;
        self.layer.borderWidth = 1;
        self.layer.masksToBounds = YES;
    }
    
    // 创建标题
    if (!X_CUSTOMMSGBOX_NOTITLE && self.title && self.title.length > 0) {
        // 调整标题布局，并加入主窗体当中
        UIView *vTitle = [self createTitle:self.title];
        rc = vTitle.frame;
        rc.origin.y += 10;
        vTitle.frame = rc;
        [self addSubview:vTitle];
        
        // 调整主窗体高度
        rcMain.size.height = vTitle.frame.origin.y + vTitle.frame.size.height;
        self.frame = rcMain;
    }
    
    // 创建消息
    BOOL bScrollMessage = NO;
    if (self.message && self.message.length > 0) {
        // 调整消息布局，并加入主窗体
        bScrollMessage = YES;
        UIView *vMessage = [self createMessage:self.message];
        rc = vMessage.frame;
        rc.origin.y = self.frame.size.height;
        if ([vMessage isKindOfClass:[UILabel class]]) {
            rc.origin.y += 15;
            bScrollMessage = NO;
        }
        vMessage.frame = rc;
        [self addSubview:vMessage];
        
        // 调整主窗体高度
        rcMain.size.height += (vMessage.frame.origin.y - self.frame.size.height) + vMessage.frame.size.height;
        self.frame = rcMain;
    }
    
    // 创建按钮
    if ([self numberOfButtons] == 1) {
        // 一个按钮
        UIButton *btn = [self createButton:[self buttonTitleAtIndex:0]
                                   atIndex:0];
        rc = btn.frame;
        rc.origin.y = self.frame.size.height;
        if (!bScrollMessage) {
            rc.origin.y += 15;
        }
        btn.frame = rc;
        [self addSubview:btn];
        
        // 调整主窗体高度
        rcMain.size.height += (btn.frame.origin.y - self.frame.size.height) + btn.frame.size.height;
        self.frame = rcMain;
    }
    else if ([self numberOfButtons] == 2) {
        // 两个按钮
        UIButton *btn = [self createButton:[self buttonTitleAtIndex:0]
                                   atIndex:0];
        rc = btn.frame;
        rc.origin.y = self.frame.size.height;
        if (!bScrollMessage) {
            rc.origin.y += 15;
        }
        rc.size.width = (rc.size.width - 10) / 2;
        btn.frame = rc;
        [self addSubview:btn];
        
        btn = [self createButton:[self buttonTitleAtIndex:1]
                         atIndex:1];
        rc = btn.frame;
        rc.origin.y = self.frame.size.height;
        if (!bScrollMessage) {
            rc.origin.y += 15;
        }
        rc.size.width = (rc.size.width - 10) / 2;
        rc.origin.x += rc.size.width + 10;
        btn.frame = rc;
        [self addSubview:btn];
        
        // 调整主窗体高度
        rcMain.size.height += (btn.frame.origin.y - self.frame.size.height) + btn.frame.size.height;
        self.frame = rcMain;
    }
    else if ([self numberOfButtons] > 0) {
        // 多个按钮
        for (NSInteger i = 0; i < [self numberOfButtons]; i++) {
            UIButton *btn = [self createButton:[self buttonTitleAtIndex:i]
                                       atIndex:i];
            rc = btn.frame;
            rc.origin.y = self.frame.size.height;
            if (!bScrollMessage) {
                rc.origin.y += 10;
            }
            btn.frame = rc;
            [self addSubview:btn];
            
            // 调整主窗体高度
            rcMain.size.height += (btn.frame.origin.y - self.frame.size.height) + btn.frame.size.height;
            self.frame = rcMain;
        }
    }
    
    rcMain.size.height += 10;
    rcMain.origin.y = ([[UIScreen mainScreen] bounds].size.height - rcMain.size.height) / 2;
    self.frame = rcMain;
    
    // 显示窗体
    [XLayerController addLayer:self];
}


@end

